
package com.twohalf.mifty.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.thrift.TException;

import club.jmint.crossing.utils.Security;
import club.jmint.mifty.dao.Sql;
import club.jmint.mifty.log.MyLog;
import club.jmint.mifty.service.MiftyService;
import com.twohalf.mifty.service.gen.SponsorService.Iface;
import com.twohalf.mifty.utils.Tools;

public class SponsorServiceImpl extends MiftyService implements Iface {
	private IIdBuilder ib = new IndexBasedIdBuilder();
	private String dbName = "db_twohalf";
	private String sponsorTable = dbName+".t_sponsor";
	private Sql ddl = Sql.getInstance();

	/**
	 * Check the given sponsor's existence by given tag 
	 * @param tag: id or mobile
	 * @return boolean
	 */
	public boolean isSponsorExist(String tag, String value){
		String querysql = "select "+tag+" from " + sponsorTable + " where "+tag+"='"+value+"'";
		List<Object[]> list = ddl.doSelect(querysql);
		if (list==null || list.size()<1){
			return false;
		} else {
			return true;
		}
	}
	
	
	/**
	 * Create a new sponsor and register it's basics
	 * @param mobile
	 * @param password
	 * @return id
	 */
	@Override
	public Map<String, String> sponsorCreate(Map<String, String> params) throws TException {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		
		//check if sponsor exists
		String mobile = params.get("mobile");
		if (isSponsorExist("mobile",mobile)){
			MyLog.logger.warn("Sponsor already exists with mobile: " + Tools.getMaskedMobile(mobile));
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_OBJECT_ALREADY_EXISTS.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_OBJECT_ALREADY_EXISTS.getInfo());
			return resultMap;
		}
		
		//create a unique product id
		String id = Integer.toString(ib.generateSponsorIdx());
		params.put("id", id);
		
		params.put("password", Tools.getEncryptPassword(params.get("password")));
		int erows = ddl.sqlCreate(sponsorTable, params);
		if (erows<0){
			MyLog.logger.error("sponsor add failed.");
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_DB_OPERATION_FAILED.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_DB_OPERATION_FAILED.getInfo());
			return resultMap;			
		}
		else if (erows==0){
		}
		else {
			MyLog.logger.info("added sponsor: " + id);
		}
		
		resultMap.put("id", id);
		return resultMap;
	}

	/**
	 * Delete a sponsor
	 * @param id
	 * @return errorCode
	 */
	@Override
	public Map<String, String> sponsorDelete(Map<String, String> params) throws TException {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		String id = params.get("id");
		String condition = "id="+id;
		
		int erows = ddl.sqlDelete(sponsorTable, condition);
		if (erows<0){
			MyLog.logger.error("sponsor delete failed.");
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_DB_OPERATION_FAILED.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_DB_OPERATION_FAILED.getInfo());
			return resultMap;			
		}
		else if (erows==0){
			MyLog.logger.warn("sponsor not exists: " + id);
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_OBJECT_NOT_EXIST.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_OBJECT_NOT_EXIST.getInfo());
			return resultMap;
		}
		else{
			MyLog.logger.info("deleted sponsor: " + id);
		}
		
		return resultMap;
	}

	/**
	 * Update sponsor table fields' value
	 * @param fields to be updated, see table t_sponsor.
	 * @return errorCode
	 */
	@Override
	public Map<String, String> sponsorUpdate(Map<String, String> params) throws TException {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		String id = params.get("id");
		String condition = "id="+id;
		
		int erows = ddl.sqlUpdate(sponsorTable, params, condition);
		if (erows<0){
			MyLog.logger.error("sponsor update failed.");
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_DB_OPERATION_FAILED.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_DB_OPERATION_FAILED.getInfo());
			return resultMap;			
		} else if (erows==0){
			MyLog.logger.warn("sponsor not exists: " + id);
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_OBJECT_NOT_EXIST.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_OBJECT_NOT_EXIST.getInfo());
			return resultMap;			
		} else {
			MyLog.logger.info("updated sponsor: " + id);
		}
		
		resultMap.put("id", id);
		return resultMap;
	}

	/**
	 * Query given sponsor table fields by id
	 * @param id
	 * @return fields' value list, see table t_sponsor
	 */
	@Override
	public Map<String, String> sponsorInfoQuery(Map<String, String> params) throws TException {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		String id = params.get("id");
		String condition = "id="+id;
		
		String fields = params.get("fields");
		String[] fieldlist = fields.split(",");
		
		List<Object[]> list = ddl.sqlSelect(sponsorTable, fields, condition);
		if (list.isEmpty()){
			MyLog.logger.warn("sponsor not exists: " + id);
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_OBJECT_NOT_EXIST.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_OBJECT_NOT_EXIST.getInfo());
			return resultMap;			
		}
		MyLog.logger.info("query sponsor: " + id);
		
		Object[] obj = list.get(0);
		for (int i=0;i<fieldlist.length;i++){
			resultMap.put(fieldlist[i], Sql.getSqlResultFieldAsString(obj[i]));
		}
		return resultMap;
	}

	/**
	 * Query all sponsor info
	 * @param offset
	 * @return sponsor object list
	 * 
	 */
	@Override
	public Map<String, String> sponsorListQuery(Map<String, String> params) throws TException {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		//String id = params.get("id");
		String condition = "id > 0";
		
		String fields = params.get("fields");
		String[] fieldlist = fields.split(",");
		
		List<Object[]> list = ddl.sqlSelect(sponsorTable, fields, condition);
		if (list.isEmpty()){
			MyLog.logger.warn("sponsors not exists.");
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_OBJECT_NOT_EXIST.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_OBJECT_NOT_EXIST.getInfo());
			return resultMap;			
		}
		MyLog.logger.info("query all sponsor.");
		
		Object[] objarr = null;
		String resobj;
		for (int idx=0;idx<list.size();idx++){
			objarr = list.get(idx);
			resobj = "{\"" + fieldlist[0] + "\",\"" + Sql.getSqlResultFieldAsString(objarr[0]) + "\"";
			for (int i=1;i<fieldlist.length;i++){
				resobj = ",\"" + fieldlist[i] + "\",\"" + Sql.getSqlResultFieldAsString(objarr[i]) + "\"";
			}
			resobj = "}";
			resultMap.put("rec_"+idx, resobj);
		}
		return resultMap;
	}

	/**
	 * Verify sponsor user and password
	 * @param mobile
	 * @param password
	 * @return errorCode
	 */
	@Override
	public Map<String, String> passwordVerify(Map<String, String> params) throws TException {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		//String id = params.get("id");
		String mobile = params.get("mobile");
		String pwdinput = Security.crossingSign(params.get("password"), "", "MD5");
		
		String fields = "id,mobile,password";
		String condition = "mobile = " + mobile;

		List<Object[]> list = ddl.sqlSelect(sponsorTable, fields, condition);
		if (list.isEmpty()){
			MyLog.logger.warn("sponsor user not exists: " + Tools.getMaskedMobile(mobile));
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_OBJECT_NOT_EXIST.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_OBJECT_NOT_EXIST.getInfo());
			return resultMap;			
		}
		Object[] obj = list.get(0);
		String pwd = ddl.getSqlResultFieldAsString(obj[2]);
		if ((pwd!=null) && pwd.equals(pwdinput)){
			//Verify ok.
			MyLog.logger.info("password verify OK: " + Tools.getMaskedMobile(mobile));
		} else {
			//Verify failed.
			MyLog.logger.error("password verify failed: " + Tools.getMaskedMobile(mobile));
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_USER_PASSWORD_INCORRECT.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_USER_PASSWORD_INCORRECT.getInfo());
		}
		
		return resultMap;
	}

	/**
	 * Change sponsor user's login password
	 * @param oldpassword
	 * @param newpassword
	 * @param id/mobile
	 * @return errorCode
	 */
	@Override
	public Map<String, String> passwordChange(Map<String, String> params) throws TException {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		String id = params.get("id");
		String mobile = params.get("mobile");
		String oldpwd = Security.crossingSign(params.get("oldpassword"), "", "MD5");
		
		String fields = "id,mobile,password";
		String condition = "mobile=" + mobile + " or id=" + id;

		List<Object[]> list = ddl.sqlSelect(sponsorTable, fields, condition);
		if (list.isEmpty()){
			MyLog.logger.warn("sponsor user not exists: " + id +"/"+Tools.getMaskedMobile(mobile));
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_OBJECT_NOT_EXIST.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_OBJECT_NOT_EXIST.getInfo());
			return resultMap;			
		}
		Object[] obj = list.get(0);
		String pwd = ddl.getSqlResultFieldAsString(obj[2]);
		if ((pwd!=null) && pwd.equals(oldpwd)){
			//Verify ok.
			MyLog.logger.info("old password verify OK: " + id +"/"+Tools.getMaskedMobile(mobile));
		} else {
			//Verify failed.
			MyLog.logger.error("old password verify failed: " + id +"/"+Tools.getMaskedMobile(mobile));
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_USER_PASSWORD_INCORRECT.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_USER_PASSWORD_INCORRECT.getInfo());
		}
		
		//do update with new password
		HashMap<String, String> fieldmap = new HashMap<String, String>();
		String newpwd = Security.crossingSign(params.get("newpassword"), "", "MD5");
		fieldmap.put("password", newpwd);
		int erows = ddl.sqlUpdate(sponsorTable, fieldmap, condition);
		if (erows<=0){
			MyLog.logger.error("sponsor user password update failed.");
			resultMap.put("errorCode", Integer.toString(ErrorCode.TWOHALF_DB_OPERATION_FAILED.getCode()));
			resultMap.put("errorInfo", ErrorCode.TWOHALF_DB_OPERATION_FAILED.getInfo());
			return resultMap;			
		}
		else {
			MyLog.logger.info("sponsor user password updated.");
		}
		
		return resultMap;
	}

}

